<template>
  <div class="train-management">
    <div class="header">
      <h2>车次管理</h2>
      <el-button type="primary" @click="showCreateDialog">
        <el-icon><Plus /></el-icon>
        添加车次
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" inline>
        <el-form-item label="起始站">
          <el-select v-model="searchForm.startStationId" placeholder="请选择起始站" clearable filterable>
            <el-option
              v-for="station in stations"
              :key="station.id"
              :label="station.stationName"
              :value="station.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="终点站">
          <el-select v-model="searchForm.endStationId" placeholder="请选择终点站" clearable filterable>
            <el-option
              v-for="station in stations"
              :key="station.id"
              :label="station.stationName"
              :value="station.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出行日期">
          <el-date-picker
            v-model="searchForm.travelDate"
            type="date"
            placeholder="请选择日期"
            value-format="YYYY-MM-DD"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchTrains">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table :data="trains" border style="width: 100%">
      <el-table-column prop="trainNumber" label="车次号" width="100" />
      <el-table-column prop="trainType" label="车次类型" width="100">
        <template #default="{ row }">
          <el-tag>{{ getTrainTypeLabel(row.trainType) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="起始站" width="120">
        <template #default="{ row }">
          {{ row.startStationName }}
        </template>
      </el-table-column>
      <el-table-column label="终点站" width="120">
        <template #default="{ row }">
          {{ row.endStationName }}
        </template>
      </el-table-column>
      <el-table-column prop="departureTime" label="发车时间" width="100" />
      <el-table-column prop="arrivalTime" label="到达时间" width="100" />
      <el-table-column prop="travelDate" label="出行日期" width="120" />
      <el-table-column prop="status" label="状态" width="80">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusLabel(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button size="small" @click="editTrain(row)">编辑</el-button>
          <el-button 
            v-if="row.status === 'ACTIVE'"
            size="small" 
            type="warning" 
            @click="cancelTrain(row.id)"
          >
            取消
          </el-button>
          <el-button size="small" type="danger" @click="deleteTrain(row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑车次对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑车次' : '添加车次'"
      width="600px"
    >
      <el-form :model="trainForm" :rules="rules" ref="trainFormRef" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="车次号" prop="trainNumber">
              <el-input v-model="trainForm.trainNumber" placeholder="请输入车次号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车次类型" prop="trainType">
              <el-select v-model="trainForm.trainType" placeholder="请选择车次类型" filterable>
                <el-option
                  v-for="type in TRAIN_TYPES"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="起始站" prop="startStationId">
              <el-select v-model="trainForm.startStationId" placeholder="请选择起始站" filterable>
                <el-option
                  v-for="station in stations"
                  :key="station.id"
                  :label="station.stationName"
                  :value="station.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="终点站" prop="endStationId">
              <el-select v-model="trainForm.endStationId" placeholder="请选择终点站" filterable>
                <el-option
                  v-for="station in stations"
                  :key="station.id"
                  :label="station.stationName"
                  :value="station.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="发车时间" prop="departureTime">
              <el-time-picker
                v-model="trainForm.departureTime"
                placeholder="请选择发车时间"
                value-format="HH:mm:ss"
                format="HH:mm"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="到达时间" prop="arrivalTime">
              <el-time-picker
                v-model="trainForm.arrivalTime"
                placeholder="请选择到达时间"
                value-format="HH:mm:ss"
                format="HH:mm"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="出行日期" prop="travelDate">
          <el-date-picker
            v-model="trainForm.travelDate"
            type="date"
            placeholder="请选择出行日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveTrain">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { trainApi, stationApi } from '@/api/train'
import { TRAIN_TYPES, TRAIN_STATUS_MAP, TRAIN_STATUS_TYPES } from '@/constants/train'
import type { Train, Station, TrainStatus, TrainType } from '@/types/train'

const trains = ref<Train[]>([])
const stations = ref<Station[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const trainFormRef = ref()

const searchForm = reactive({
  startStationId: null as number | null,
  endStationId: null as number | null,
  travelDate: null as string | null
})

const trainForm = reactive({
  id: null as number | null,
  trainNumber: '',
  trainType: '' as TrainType,
  startStationId: null as number | null,
  endStationId: null as number | null,
  departureTime: '',
  arrivalTime: '',
  travelDate: ''
})

const rules = {
  trainNumber: [
    { required: true, message: '请输入车次号', trigger: 'blur' }
  ],
  trainType: [
    { required: true, message: '请选择车次类型', trigger: 'change' }
  ],
  startStationId: [
    { required: true, message: '请选择起始站', trigger: 'change' }
  ],
  endStationId: [
    { required: true, message: '请选择终点站', trigger: 'change' }
  ],
  departureTime: [
    { required: true, message: '请选择发车时间', trigger: 'change' }
  ],
  arrivalTime: [
    { required: true, message: '请选择到达时间', trigger: 'change' }
  ],
  travelDate: [
    { required: true, message: '请选择出行日期', trigger: 'change' }
  ]
}

// 获取车次列表
const fetchTrains = async () => {
  try {
    const response = await trainApi.getAllTrains()
    if (response.success) {
      trains.value = response.data
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('获取车次列表失败:', error)
    ElMessage.error('获取车次列表失败')
  }
}

// 获取车站列表
const fetchStations = async () => {
  try {
    const response = await stationApi.getAllStations()
    if (response.success) {
      stations.value = response.data
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('获取车站列表失败:', error)
    ElMessage.error('获取车站列表失败')
  }
}

// 搜索车次
const searchTrains = async () => {
  if (!searchForm.startStationId || !searchForm.endStationId || !searchForm.travelDate) {
    ElMessage.warning('请完整填写搜索条件')
    return
  }
  
  try {
    const response = await trainApi.searchTrains(
      searchForm.startStationId,
      searchForm.endStationId,
      searchForm.travelDate
    )
    if (response.success) {
      trains.value = response.data
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('搜索车次失败:', error)
    ElMessage.error('搜索车次失败')
  }
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    startStationId: null,
    endStationId: null,
    travelDate: null
  })
  fetchTrains()
}

// 显示创建对话框
const showCreateDialog = () => {
  resetForm()
  isEdit.value = false
  dialogVisible.value = true
}

// 编辑车次
const editTrain = (train: Train) => {
  Object.assign(trainForm, train)
  isEdit.value = true
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  Object.assign(trainForm, {
    id: null,
    trainNumber: '',
    trainType: '',
    startStationId: null,
    endStationId: null,
    departureTime: '',
    arrivalTime: '',
    travelDate: ''
  })
  trainFormRef.value?.clearValidate()
}

// 保存车次
const saveTrain = async () => {
  try {
    const valid = await trainFormRef.value.validate()
    if (!valid) return
    
    if (trainForm.startStationId === null || trainForm.endStationId === null) {
      ElMessage.error('请选择起始站和终点站')
      return
    }
    
    if (trainForm.startStationId === trainForm.endStationId) {
      ElMessage.error('起始站和终点站不能相同')
      return
    }
    
    const trainData = {
      trainNumber: trainForm.trainNumber,
      trainType: trainForm.trainType,
      startStationId: trainForm.startStationId,
      endStationId: trainForm.endStationId,
      departureTime: trainForm.departureTime,
      arrivalTime: trainForm.arrivalTime,
      travelDate: trainForm.travelDate
    }
    
    let response
    if (isEdit.value && trainForm.id !== null) {
      response = await trainApi.updateTrain(trainForm.id, trainData)
    } else {
      response = await trainApi.createTrain(trainData)
    }
    
    if (response.success) {
      ElMessage.success(response.message)
      dialogVisible.value = false
      fetchTrains()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error(isEdit.value ? '更新车次失败' : '创建车次失败', error)
    ElMessage.error(isEdit.value ? '更新车次失败' : '创建车次失败')
  }
}

// 取消车次
const cancelTrain = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要取消这个车次吗？', '确认取消', {
      type: 'warning'
    })
    
    const response = await trainApi.cancelTrain(id)
    if (response.success) {
      ElMessage.success(response.message)
      fetchTrains()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消车次失败:', error)
      ElMessage.error('取消车次失败')
    }
  }
}

// 删除车次
const deleteTrain = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个车次吗？', '确认删除', {
      type: 'warning'
    })
    
    const response = await trainApi.deleteTrain(id)
    if (response.success) {
      ElMessage.success(response.message)
      fetchTrains()
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除车次失败:', error)
      ElMessage.error('删除车次失败')
    }
  }
}

// 获取车次类型标签
const getTrainTypeLabel = (type: TrainType) => {
  const trainType = TRAIN_TYPES.find(t => t.value === type)
  return trainType ? trainType.label : type
}

// 获取状态标签
const getStatusLabel = (status: TrainStatus) => {
  return TRAIN_STATUS_MAP[status] || status
}

// 获取状态类型
const getStatusType = (status: TrainStatus) => {
  return TRAIN_STATUS_TYPES[status] || 'info'
}

onMounted(() => {
  fetchTrains()
  fetchStations()
})
</script>

<style scoped>
.train-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.search-area {
  background: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
}
</style>